<?php

namespace Users\Recover;

use Pinenut\Action;
use Pinenut\Form;
use Pinenut\User\Auth\EmailPassword;
use Users\Recover\GenerateCodeFormConfig as FormConfig;
use Pinenut\Mail;

class GenerateCodeAction extends Action {

	protected static $layout = "#layouts.column1Narrow";

	public function run() {
		$formConfig = FormConfig::get();
		$form = new Form($this->request->getSessionId(), 'generateCode', $formConfig);

		if ($this->request->isPost() && $this->request->isAjax()) {
			$form->process($this->request->params(), true);
			$this->response->content = $form->render();
			$this->response->noRender(true);
			return;
		} else if ($this->request->isPost() && !$this->request->onlyRender) {
			if (!$form->process($this->request->params())) {
				$this->response->form = $form;
				return;
			}

			$code = EmailPassword::generateRecoveryCode($this->request->email);

			$mail = new Mail();
			$mail->to = $this->request->email;
			$mail->subject = 'Recovery Code';
			$mail->content = 'Your recover code: '. $code;
			$mail->send();	
			$this->redirect($this->url('users.recover.checkCode'));
			
			return;
		}

		$this->response->form = $form;
	}

}
